import os

import cv2
import numpy as np


def split():
    # 1. 读取图像（彩色或灰度都行，但处理前需要转换为灰度）
    imgPath = "E:\code\split03.png"
    # 1. 读取图像
    img = cv2.imread(imgPath)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    _, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

    contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    output_dir = "spots_alpha"
    os.makedirs(output_dir, exist_ok=True)

    count = 0
    for cnt in contours:
        area = cv2.contourArea(cnt)
        perimeter = cv2.arcLength(cnt, True)
        if perimeter == 0:
            continue
        circularity = 4 * np.pi * area / (perimeter ** 2)

        if circularity > 0.7 and area > 50:
            (x, y), radius = cv2.minEnclosingCircle(cnt)
            x = int(x)
            y = int(y)
            radius = int(radius)

            # 定义正方形裁剪区域
            x1 = max(0, x - radius)
            y1 = max(0, y - radius)
            x2 = min(img.shape[1], x + radius)
            y2 = min(img.shape[0], y + radius)
            cropped_bgr = img[y1:y2, x1:x2]

            # 创建与裁剪图像一样大小的 alpha mask
            mask = np.zeros((y2 - y1, x2 - x1), dtype=np.uint8)
            cv2.circle(mask, (radius, radius), radius, 255, -1)  # 在中心画白圆（255表示不透明）

            # 将BGR图像转为BGRA（加Alpha通道）
            b, g, r = cv2.split(cropped_bgr)
            rgba = cv2.merge((b, g, r, mask))

            # 保存为PNG，背景透明
            output_path = os.path.join(output_dir, f"spot_{count + 1}.png")
            cv2.imwrite(output_path, rgba)
            count += 1

    print(f"已保存 {count} 个透明背景光斑图像到文件夹：{output_dir}")


    return output_dir+"\\"+f"spot_{count}.png"

def read(imgPath):
    # 读取图片（以 BGR 格式）
    # image = cv2.imread('E:\\wifi\\asdasd.png')
    image = cv2.imread(imgPath)

    # 检查图片是否成功读取
    if image is None:
        raise FileNotFoundError("图像文件未找到")

    # 将图像转换为 float 类型，避免溢出
    image = image.astype(np.float32)

    # 计算每个通道的平均值（BGR 顺序）
    mean_per_channel = cv2.mean(image)[:3]  # 忽略 alpha 通道（如果有）

    # 转换为 RGB 顺序
    mean_rgb = (mean_per_channel[2], mean_per_channel[1], mean_per_channel[0])

    y, x, ch1 = image.shape
    print(f"high:{y},{x},{ch1}")

    print("RGB 平均值:", mean_rgb)


if __name__ == '__main__':
    outpath = split()
    read(outpath)

